package com.xiaohao.employee_attendance.controller;

import com.xiaohao.employee_attendance.bean.Department;
import com.xiaohao.employee_attendance.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2019-03-09 20:34
 * @package com.xiaohao.employee_attendance.controller
 * @description
 */
@Controller
public class DeptController {
    @Autowired
    DeptService deptService;

    @RequestMapping("dept/deptSearch")
    public String deptSearch(@RequestParam(defaultValue = "0") int page, Model model) {

        Page<Department> byPage = deptService.getByPage(page, 5);
        model.addAttribute("depts", byPage);
        return "dept/deptSearch";

    }


    @RequestMapping("dept/deptSearchByName")
    @ResponseBody
    public Department deptSearch(String deptname) {
        System.out.println(deptname);
        return deptService.getByName(deptname);

    }

    @RequestMapping("dept/deptUpdate")
    public String deptUpdate(int id, Model model) {
        System.out.println(id);
        Department byId = deptService.findById(id);

        List<Department> allDept = deptService.findAllDept();

        List list = new ArrayList();
        for (Department department : allDept) {
            list.add(department.getManager());
        }
        model.addAttribute("dept", byId);
        model.addAttribute("manager", list);
        return "dept/deptUpdate";

    }


    @RequestMapping("dept/deptSave")
    public String deptSave(Department department) {

        Department byId = deptService.findById(department.getDepartmentId());

        if (byId == null) {
            department.setTotalUser(0);
            department.setCreateTime(LocalDate.now());
            deptService.deptSave(department);
        } else {
            byId.setManager(department.getManager());
            byId.setDepartmentName(department.getDepartmentName());
            deptService.deptSave(byId);
        }
        return "forward:deptSearch";

    }


    @RequestMapping("dept/deptDelete")
    @ResponseBody
    public void deptDelete(int id) {
        deptService.deptDeleteById(id);
    }

    @RequestMapping("dept/deptInsert")
    public String deptInsert(Department department) {
        department.setCreateTime(LocalDate.now());
        department.setTotalUser(0);
        deptService.deptSave(department);
        return "forward:deptSearch";

    }


}
